<template>
	<view class="order-check-page">
		<image class="topBg" :src="orderImgUrl+'security-check-bg.png'"></image>
		<!-- style="min-height: 30vh;  max-height: 72vh;overflow-y: scroll;" -->
		<view style="min-height: 0vh;  max-height: 72vh;overflow-y: scroll;">
			<view class="p-list" v-for="(item,index) in list" :key="index">
				<view class="p-l-item">
					<text style="font-weight: 800;font-size: 30rpx;color: #000000;">{{index+1}}.{{item.name}}: </text>   <text v-for="cItem in item.list">{{cItem.name}}?</text>
					<view class="p-btn c-flex jc-between" >
						<view  :class="item.pass ===true?'normal':''" @tap="btnHandler(item,true)">合格</view>
						<view :class="item.pass ===false?'error':''" @tap='btnHandler(item,false)'>异常</view>	
					</view>
					<textarea v-if="item.pass ===false" class="remarks"  placeholder-style="color:#8B959F;font-size: 28rpx;" v-model="item.reason" placeholder="备注异常原因…"></textarea>
				</view>
				
			</view>
		</view>
		<view class="title-con c-flex jc-between c-item-center" style="margin: 8px 15px 15px;">
			<view class="c-flex jc-start c-item-center">
				<view class="d_icon"></view>
				<view class="title-1"><text>拍照记录</text></view>
			</view>
		
		</view>
		<view class="phone_panel c-flex c-flex-wrap">
			<view class="view_phone" v-for="(item,index) in sceneImgList">
				<image class="closeBtn" :src='remoteImgCommonUrl+"close@2x.png"' @tap.stop="delImg(index,'scene')"></image>
				<image :src="item" @tap.stop='previewFile(index,sceneImgList)'></image>
			</view>
			<view class="add_phone" @tap='upload_image()' v-if='sceneImgList.length<num'>
				<image src="@/static/images/common/sm-capture-img.png"></image>
				<view>添加照片</view>
			</view>
		</view>
		<view class="tip">
			* 关键部位(瓶、管、灶具、调压阀、用气环境、侧漏照片)至少上传一张照片!
		</view>
		<view class="submitBtn" @tap="submitHandler">
			提交并签字
		</view>
		<view style="height: 70rpx;"></view>
		<WaterMark ref="watermark"  :fontSize="40" :fontColor="'#E86748'" :markAlign="'bottomRight'" style="transform:translate(-9999px, 0px);"
								@waterMark="waterMarkFun"></WaterMark>
	</view>
</template>

<script>
	import {
		aliOssParams
	} from '@/utils/oss/oss.js';
	import {
		toast,getNowTime
	} from '@/utils/utils.js';
	import WaterMark from '@/components/waterMark/waterMark.vue';
	
	export default {
		components:{WaterMark},
		data() {
			return {
				url: 'https://tyd-worksite.oss-cn-beijing.aliyuncs.com',
				remoteImgCommonUrl: this.$API.IMG_URL + '/tower-install/',
				remoteImgUrl: this.$API.IMG_URL + '/construct-supervision-mp/',
				orderImgUrl: this.$API.IMG_URL + '/gas/yehuaqi/order/',
				commonUrl: this.$API.IMG_URL + '/common/',
				userId:null,
				list: [],
				sceneImgList: [],
				attachments:'',
				roomItem:null,
				inspectType:null,
				type:null,
				checkId:null,
				num:10,
				addr:'',
				currAddr:'',
				latitude:'',
				longitude:''
			};
		},
		onLoad(options) {
			this.roomItem = JSON.parse(options.item);
			console.log(this.roomItem)
			
			this.checkId = this.roomItem.id;
			this.type = options.type;
			if(this.type==='order'){
				this.addr = this.roomItem.lpgUserAddress;
				if(this.roomItem.lpgUserType===0){
					this.inspectType = 21
				}else if(this.roomItem.lpgUserType===1){
					this.inspectType = 22
				}else if(this.roomItem.lpgUserType===2){
					this.inspectType = 23
				}
				
			}else{
				this.addr =this.roomItem.street+this.roomItem.villageName+this.roomItem.address;
				if(this.roomItem.type===0){
					this.inspectType = 21
				}else if(this.roomItem.type===1){
					this.inspectType = 22
				}else if(this.roomItem.type===2){
					this.inspectType = 23
				}
				
			}
			this.initData()
			uni.setNavigationBarColor({
				backgroundColor:'#f9ead5',
				frontColor: '#000000'
			});
			this.getCurrAddr();
			
		},
		
		methods: {
			getCurrAddr(){
				let that = this;
				this.qqmapsdk.reverseGeocoder({
					
					success: function(res) { //成功后的回调
					
						let data = res.result.address_reference.landmark_l1 || res.result.address_reference
							.landmark_l2;
							console.log('当前位置:',res)
							that.currAddr = data.title;
							//result.formatted_addresses
							//result.formatted_addresses.standard_address
						// that.curr_address = data.title || '腾渊达集团';
						that.latitude = data.location.lat;//纬度
						that.longitude = data.location.lng;//经度
				
					},
					fail: function(error) {
						toast(error);
					},
					complete: function(res) {
						//console.log(res);
					}
				})
			},
			btnHandler(item,bool){
				
				console.log(item)
				this.$nextTick(()=>{
					item.pass = bool;
					if(item.pass===false){
						item.reason = '';
					}
				})
			},
			countCommonChars(str1, str2) {
			    const set1 = new Set(str1); // 将str1转换为Set以便去重和快速查找
			    const commonChars = [...str2].filter(char => set1.has(char)); // 过滤出在set1中的字符
			    return commonChars.length; // 返回共有字符的数量
			},
			 
			
			
			submitHandler(){
				const bool=	this.list.every((item)=>{
					return item.pass !==null 
				})
				console.log(bool)
				if(!bool){
					toast('还有未安检的项目')
					return
				}
				const arr=[];
				this.list.forEach(item=>{
					arr.push({"itemId": item.itemId, "pass": item.pass,"reason":item.reason})
				})
				if(this.sceneImgList.length<6){
					toast('安检照片至少上传6张')
					return
				}
			
				 //this.currAddr='腾渊达集团'
				 //console.log(countCommonChars(str1, str2)); // 输出：0，因为没有相同的字符
				 // if(countCommonChars(str1, str2)<4){
					//  toast('安检地址与订单地址不匹配')
					//  return
				 // }
				// if (this.addr.indexOf(this.currAddr) === -1) {
				// 	toast('安检地址与订单地址不匹配')
				// 	return;
				// }
				
				this.attachments = this.sceneImgList.toString();
				console.log(this.checkId,this.attachments,this.type)
				
				uni.navigateTo({
					url:'./signature?id='+this.checkId+'&data='+JSON.stringify(arr)+'&attachments='+this.attachments+'&checkType='+this.type
				})
			},
			initData() {
				this.$API.liquefiedGasRoomYearCheackItem({inspectType:this.inspectType }).then(res =>{
					let arr=res.list; //追加新数据
					arr.map(item=>{
						item.itemId =item.id;
						item.pass =null;
						item.reason ='';
					})
					this.list = arr;	
				}).catch(()=>{
					//联网失败, 结束加载
					
				});
			},
			orderData(){
				this.$API.liquefiedGasSecurityList({inspectType:this.inspectType }).then(res =>{
					let arr=res.list; //追加新数据
					arr.map(item=>{
						item.itemId =item.id;
						item.pass =null;
						item.reason ='';
					})
					this.list = arr;	
				}).catch(()=>{
					//联网失败, 结束加载
					
				});
			},
			delImg(idx) {
				this.sceneImgList.splice(idx, 1);
				 
			},
			upload_image() {
				let that = this;
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['camera'], //从相册选择
					success: function(res) {
						console.log(JSON.stringify(res.tempFilePaths));
						const tempFilePaths = res.tempFilePaths;
						
						var fillTexts = [];
						// if(that.currAddr){
							
						// 	// fillTexts.push("上传位置：" + that.currAddr);
						// 	// fillTexts.push("上传时间：" + getNowTime()); 
							
						// 	fillTexts.push("经度：" + that.longitude);
						// 	fillTexts.push("纬度：" + that.latitude); 
						// }
						
						
						//that.$refs.watermark.addWaterMark({tempFilePaths,fillTexts});
						
						for (let i = 0; i < tempFilePaths.length; i++) {
							that.getAccessInfo(tempFilePaths[i]);
						}						
												

						
					}
				});
			
			
			
			},
			/**
			 * 水印添加回调，在H5平台下，filePath 为 base64
			 */
			waterMarkFun(filePath){
				console.log('filepath',filePath)
				this.getAccessInfo(filePath);
					
			},
			previewFile(index, imgArr) {
				uni.previewImage({
					current: index, //预览图片的下标
					urls: imgArr, //预览图片的地址，必须要数组形式，如果不是数组形式就转换成数组形式就可以
					loop: true,
					indicator: 'default'
				});
			},
			getAccessInfo(filePath) {
				this.$API.getAccessInfo('iot-auth').then(res => {
					if (res.code == 0) {
						var accessInfo = res.data;
						const {
							accessKeySecret,
							accessKeyId,
							expiration,
							securityToken
						} = accessInfo;
						var obj = aliOssParams(accessKeyId, accessKeySecret, expiration, securityToken, this.url,
							'png', 'image/tyd-worksite/gas/');
						if (obj) {
							this.uploadProgress(filePath, obj);
						} else {
							toast('数据错误，请重新上传');
						}
					}
			
				})
			},
			
			uploadProgress(filePath, obj) {
				let that = this;
				uni.showLoading({
					title: '上传中...',
					icon: 'none'
				})
			
				const uploadTask = uni.uploadFile({
					url: obj.host,
					filePath: filePath,
					name: 'file',
					formData: {
						'key': obj.fileName,
						'policy': obj.policy,
						'OSSAccessKeyId': obj.aid,
						'signature': obj.signature,
						'x-oss-security-token': obj.securityToken,
						'success_action_status': '200'
			
					},
					success: function(uploadFileRes) {
						console.log(uploadFileRes);
						if (uploadFileRes.statusCode == 200) {
			
							let imgUrl = that.url + '/' + obj.fileName;
							that.sceneImgList.push(imgUrl);
							uni.hideLoading()
							toast('上传成功');
						} else {
							toast('上传失败');
							uni.hideLoading()
						}
			
					},
					fail(err) {
						console.log('error:', err);
						toast('上传失败');
						uni.hideLoading()
						//that.$refs.popup.close();
					}
				});
			
				
			
			}

			
		}
	}
</script>
<style lang="scss" scoped>
	.order-check-page {
		.tip{
			margin: 8px 15px 8px;
			font-size: 24rpx;
			color: #E86547;
		}
		.d_icon {
			margin-right: 10rpx;
			width: 14rpx;
			height: 32rpx;
			background: linear-gradient(180deg, #F18858 0%, #E86547 100%);
			transform: skewX(-12deg)
		}
		position: relative;
		background-image: linear-gradient(rgba(249, 195, 115, .3) 0%, #F9F9F9 100%);
		height: 100%;

		.topBg {
			width: 676rpx;
			height: 192rpx;
			margin-top: 20rpx;
			    margin-left: 28rpx;
		}



		.p-list {
			margin: 0rpx 18rpx 0;

			.p-l-item {
				background: #FFFFFF;border-radius: 18rpx;padding: 35rpx 28rpx 35rpx;margin-bottom: 20rpx;position: relative;font-family: PingFang-SC, PingFang-SC;font-weight: 400;font-size: 28rpx;color: #000000;
			}
			
		}
		.remarks{
			margin: 20rpx auto;
			width: 602rpx;
			height: 126rpx;
			border-radius: 16rpx;
			border: 2rpx solid #DEDEDE;
			padding: 20rpx 22rpx;
		}
		.p-btn {
			margin-top: 35rpx;
			font-family: PingFang-SC, PingFang-SC;
			font-weight: 500;
			font-size: 28rpx;
			text-align: center;
			color: #000;
			view {
				margin: 0 auto;
				width: 320rpx;
				height: 82rpx;
				background: #F6F5F8;
				border-radius: 16rpx;
				line-height: 82rpx;
			}

			.error{
				background: rgba(208,2,27,0.1);
				color: #D0021B;
			}
			.normal{
				background: rgba(26,186,105,0.1);
				color: #1ABA69;
			}
		}
		.submitBtn{
			width: 710rpx;
			height: 84rpx;
			line-height: 84rpx;
			background: linear-gradient( 180deg, #F18858 0%, #E86547 100%);
			border-radius: 16rpx;
			border: 2rpx solid #E96949;
			margin: 0 auto;
			top:40rpx;
			position: relative;
			//bottom: 30rpx;
			// left: 50%;
			// transform: translate(-50%,-50%);
			font-family: PingFang-SC, PingFang-SC;
			font-weight: 500;
			font-size: 28rpx;
			text-align: center;
			color: #fff;
			
		}
		.phone_panel {
			//margin-top: 32rpx;
			background: #FFFFFF;
			border-radius: 20rpx;
			gap: 42rpx;
			padding: 48rpx 34rpx;
			margin: 23rpx 18rpx 0;
			.view_phone {
				width: 300rpx;
				height: 200rpx;
				border-radius: 10rpx;
				position: relative;
		
				//margin:48rpx 34rpx;
				image {
		
					width: 100%;
					height: 100%;
					border-radius: 10rpx;
				}

				.closeBtn {
					width: 32rpx;
					height: 32rpx;
					position: absolute;
					top: 5rpx;
					right: 4rpx;
				}
			}
		
			.add_phone {
				width: 300rpx;
				height: 200rpx;
				border-radius: 10rpx;
				border: 2rpx dashed #D2D2D2;
				//margin:48rpx 34rpx;
				text-align: center;
		
				image {
					margin-top: 55rpx;
					width: 40rpx;
					height: 42rpx;
				}
		
				view {
					font-size: 20rpx;
					font-family: PingFangSC-Medium, PingFang SC;
					font-weight: 500;
					color: #9B9B9B;
				}
		
			}
		}
		
	}
</style>